#include <functional>
#include <QMetaType>
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include "qt_post.h"
void qt_post::do_post(qt_post_fun func,bool bBlock)
{
	if (qApp!=nullptr && QThread::currentThread()==qApp->thread())
	{
		(func)();
	}
	else
	{
		if (bBlock)
		{
			emit post_block(func);
		}
		else
		{
			emit post(func);
		}
	}
}

void qt_post::do_post_c( qt_c_post_fun func,bool bBlock )
{
	if (QThread::currentThread()==qApp->thread())
	{
		(func)();
	}
	else
	{
		if (bBlock)
		{
			emit post_block(func);
		}
		else
		{
			emit post(func);
		}
	}
}

qt_post::qt_post()
{
	//moveToThread(qApp->thread());
	qRegisterMetaType<qt_post_fun>("qt_post_fun");
	bool bConnected=connect(this, SIGNAL(post(qt_post_fun)), this, SLOT(on_post(qt_post_fun)), Qt::QueuedConnection);
	bConnected=connect(this, SIGNAL(post_block(qt_post_fun)), this, SLOT(on_post(qt_post_fun)),
		Qt::BlockingQueuedConnection);

	qRegisterMetaType<qt_post_fun>("qt_c_post_fun");
	bConnected=connect(this, SIGNAL(post_c(qt_c_post_fun)), this, SLOT(on_post_c(qt_c_post_fun)), Qt::QueuedConnection);
	bConnected=connect(this, SIGNAL(post_c_block(qt_c_post_fun)), this, SLOT(on_post_c(qt_c_post_fun)),
		Qt::BlockingQueuedConnection);
	
}

void qt_post::on_post( qt_post_fun qfunc_ptr )
{
	 (qfunc_ptr)();
}

void qt_post::on_post_c( qt_c_post_fun qfunc_ptr )
{
	(qfunc_ptr)();
}

qt_post& qt_post::the_post()
{
	static qt_post qt_post_instance;
	return qt_post_instance;
}


SIMPLESTRATEGYLIB_EXPORT void post_ui(qt_post_fun func)
{
	qt_post::the_post().do_post(func,false);
}

SIMPLESTRATEGYLIB_EXPORT void post_ui_block(qt_post_fun func)
{
	qt_post::the_post().do_post(func,true);
}



SIMPLESTRATEGYLIB_EXPORT void post_c_ui(qt_c_post_fun func)
{
	qt_post::the_post().do_post_c(func,false);
}

SIMPLESTRATEGYLIB_EXPORT void post_c_ui_block(qt_c_post_fun func)
{
	qt_post::the_post().do_post_c(func,true);
}
